package com.itcast.homework.service;

import cn.hutool.json.JSONUtil;
import com.itcast.homework.pojo.Sku;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ESService {

    @Autowired
    private SkuService skuService;

    /**
     * 创建索引库和mapping映射
     * @param client
     * @throws Exception
     */
    public void createIndexAndMapping(RestHighLevelClient client) throws Exception {
        //创建索引库
        CreateIndexRequest request = new CreateIndexRequest("sku");
        //设置分片和备份
        request.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
        );
        //设置mapping映射
        request.mapping("{\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": true\n" +
                "      },\n" +
                "      \"sn\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": true\n" +
                "      },\n" +
                "      \"name\": {\n" +
                "        \"type\": \"text\",\n" +
                "        \"index\": true\n" +
                "      },\n" +
                "      \"price\" : {\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"num\": {\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"alert_num\": {\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"image\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"images\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"weight\": {\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"create_time\": {\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"update_time\": {\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"spu_id\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": true\n" +
                "      },\n" +
                "      \"category_id\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": true\n" +
                "      },\n" +
                "      \"category_name\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": true\n" +
                "      },\n" +
                "      \"brand_name\": {\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": true\n" +
                "      },\n" +
                "      \"spec\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"sale_num\": {\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"comment_num\": {\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"status\": {\n" +
                "        \"type\": \"integer\"\n" +
                "      }\n" +
                "    }\n" +
                "  }", XContentType.JSON);

        //发起请求
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        //查看结果
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println("acknowledged = " + acknowledged);

        client.close();
    }

    /**
     * 从数据库查询数据,像索引库添加数据
     * @param client
     * @throws Exception
     */
    public void addDocument(RestHighLevelClient client) throws Exception {

        IndexRequest request = new IndexRequest("sku");

        List<Sku> skuList = skuService.queryAllSku();
        for (Sku sku : skuList) {
            request.id(sku.getId());
            String skuJson = JSONUtil.toJsonStr(sku);
            request.source(skuJson, XContentType.JSON);
            IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
            System.out.print(indexResponse.status());
        }
        client.close();
    }

    /**
     * 查询文档数量
     * @param client
     * @throws Exception
     */
    public void queryAllDocument(RestHighLevelClient client) throws Exception {
        SearchRequest searchRequest = new SearchRequest("sku");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchSourceBuilder.trackTotalHits(true);

        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        long total = searchResponse.getHits().getTotalHits().value;
        System.out.println("total = " + total);

        client.close();
    }

    /**
     * 删除索引库
     * @param client
     * @throws Exception
     */
    public void deleteIndex(RestHighLevelClient client) throws Exception {
        DeleteIndexRequest request = new DeleteIndexRequest("sku");
        AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
        boolean acknowledged = deleteIndexResponse.isAcknowledged();
        System.out.println("acknowledged = " + acknowledged);
        client.close();
    }
}
